package com.example.controller.redis;

import com.example.component.common.RedisUtil;
import com.example.constant.redis.RedisKeyConstant;
import com.example.service.common.Closure;
import com.example.service.redis.TestService;
import com.example.pojo.vo.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Set;

/**
 * @author LiYuhang
 * @version 0.1
 * @application cache TestController
 * CacheAside Pattern
 * 读 先读缓存 缓存没有 读数据库
 * 写 先写数据库 再删除缓存
 * @Date 2020/9/23 10:34
 */
@RestController
@RequestMapping("test1")
@Slf4j(topic = "CACHE-TestController1")
public class TestController1 {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    @Qualifier(value = "redisTemplate")
    RedisTemplate redisTemplate;

    @Autowired
    TestService testService;

    @PostConstruct
    public void init() {
        redisUtil.setRedisTemplate(redisTemplate);
    }

    /**
     * 合理设置 redis key便于删除缓存
     * 实际开发 可设置一个baseTypeCode 分组
     * http://localhost:8082/test1/search?param1=key1&param2=value1&param3=ces1
     * http://localhost:8082/test1/search?param1=key2&param2=value2&param3=ces2
     * http://localhost:8082/test1/search?param1=key3&param2=value3&param3=ces3
     * @param param1
     * @param param2
     * @param param3
     * @return
     */
    @RequestMapping(value = "search")
    public Result search(String param1,String param2,String param3){
        String[] params= {param1,param2,param3};
        String redisKey=RedisKeyConstant.REDEI_KEY+":"+ Arrays.toString(params);
        Object data=redisUtil.getCache(redisKey,new Closure<Object, String>() {
            @Override
            public Object execute(String redisKey) {
                // 执行你的业务逻辑
                log.info("从数据库读取data redisKey:{}",redisKey);
                return testService.getDataList();
            }
        });
        return Result.OK(data);
    }

    /**
     *
     * @return
     */
    @RequestMapping(value = "write")
    public Result write( ){
        //write to Database
        boolean flag=testService.writToDb();
        if(flag){
            //获取所有 RedisKeyConstant.REDEI_KEY： 开头的key  删除多个key
            Set<String> keySet=redisTemplate.keys(RedisKeyConstant.REDEI_KEY+":*");
            String[] keys=keySet.toArray(new String[keySet.size()]);
            redisUtil.del(keys);
            return Result.OK("数据更新成功");
        }else{
            return Result.error("数据修改失败");
        }
    }

}
